<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>WebSocket初试</title>
    <style>
        .content{
            width: 300px;
            height: 300px;
            border: 1px solid #000;
        }
    </style>
</head>
<body>
    <input type="text" id="ipt">
    <button id="btn">点击发送</button>
    <div class="content"></div>
    <script>
        var ipt  = document.querySelector('#ipt')
        var btn = document.querySelector('#btn')
        var content = document.querySelector('.content')

        var socket = new WebSocket("ws://localhost:3000")
        socket.addEventListener('open', function(){
            content.innerHTML = '连接成功'
        })
        // 主动发送消息
        btn.addEventListener('click', function(){
            socket.send(ipt.value)
        })
        // 接受消息
        socket.addEventListener('message', function(e){
            console.log(e)
            var newli = document.createElement('li')
            resp = JSON.parse(e.data)
            if (resp.type===0){
                newli.style.color = 'green'
            }else if(resp.type===2){
                newli.style.color = 'red'
            }
            newli.innerHTML = resp.msg + resp.date
            content.appendChild(newli)
        })
    </script>
</body>
</html>